#include <stdio.h>
#include <stdlib.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <sys/types.h>
#include <string.h>
#include <unistd.h>
#include <sys/select.h>

int main(void)
{
	int fd;
	int ret;

	/*买电话*/
	fd = socket(AF_INET, SOCK_STREAM, 0);
	if (fd == -1) {
		perror("socket");
		exit(1);
	}
	int on = 1;
	setsockopt(fd,SOL_SOCKET,SO_REUSEADDR,&on,sizeof(on)); //重用端口号 on 设置为真

	/*绑定电话卡（可选）*/
#if 1
	struct sockaddr_in client;
	client.sin_family = AF_INET; //ipv4
	client.sin_addr.s_addr = inet_addr("192.168.104.89");
	client.sin_port = htons(12000); //转成大端

	ret = bind(fd, (struct sockaddr *)&client, sizeof(client));
	if (ret == -1) 
	{
		perror("bind");
		exit(1);
	}
#endif

	/*打电话*/
	struct sockaddr_in server;
	server.sin_family = AF_INET;
	server.sin_addr.s_addr = inet_addr("192.168.104.89");
	server.sin_port = htons(12001);
	ret = connect(fd, (struct sockaddr *)&server, sizeof(server));	
	if (ret == -1) {
		perror("connect");
		exit(1);
	}

	/*发送和接收*/
	fd_set readset;
	char buf[50] ;
	while (1) 
	{
		FD_ZERO(&readset);//清空集合
		FD_SET(STDIN_FILENO, &readset); //键盘
		FD_SET(fd, &readset);//服务端
		ret = select(fd+1,&readset,NULL,NULL,NULL);
		printf("select return:%d\n", ret);
		
		//键盘就绪
		if (FD_ISSET(STDIN_FILENO, &readset)) 
		{
			bzero(buf, 50);
			fgets(buf, 50, stdin);
			ret = send(fd, buf, strlen(buf), 0);
			if (strncmp(buf, "quit", 4) == 0) break;
		}
		//服务端就绪
		if (FD_ISSET(fd, &readset))
		{
			bzero(buf, 50);
			ret = read(fd, buf, sizeof(buf));
			if (ret == 0) 
			{
				printf("client offline\n");
				break;
			}
			if (ret < 0) 
			{
				perror("read");
				continue;
			}
			printf("recv info: %s", buf);
			if (strncmp(buf, "quit", 4) == 0) break;
		}
	}
	
	/*挂电话*/
	close(fd);
	
	return 0;
}

